package cn.lcsjsxy.yxc.collections_framework.Map;

import cn.lcsjsxy.yxc.collections_framework.Collection.Person;
import org.junit.jupiter.api.Test;

import java.util.*;

public class TreeMapTest {
    //向TreeMap中添加key-value，要求key必须是由同一个类创建的对象
    //因为要按照key进行排序：自然排序、定制排序

    //自然排序
    @Test
    public void test1(){
        TreeMap map=new TreeMap();
        map.put(new Person("xyz",22),699);
        map.put(new Person("ayz",21),562);
        map.put(new Person("gyz",24),321);
        map.put(new Person("yyz",16),985);

        Set entrySet=map.entrySet();
        Iterator iterator= entrySet.iterator();
        while (iterator.hasNext()){
            Object obj=iterator.next();
            Map.Entry entry=(Map.Entry) obj;
            System.out.println(entry.getKey()+"-->"+entry.getValue());
        }
    }

    //定制排序
    @Test
    public void test2(){
        TreeMap map=new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Person && o2 instanceof Person){
                    Person p1=(Person) o1;
                    Person p2=(Person) o2;
                    return Integer.compare(p1.getAge(),p2.getAge());
                }
                throw new RuntimeException("输入的类型不匹配");
            }
        });

        map.put(new Person("xyz",22),699);
        map.put(new Person("ayz",66),562);
        map.put(new Person("gyz",32),321);
        map.put(new Person("yyz",21),985);

        Set entrySet=map.entrySet();
        Iterator iterator= entrySet.iterator();
        while (iterator.hasNext()){
            Object obj=iterator.next();
            Map.Entry entry=(Map.Entry) obj;
            System.out.println(entry.getKey()+"-->"+entry.getValue());
        }
    }
}
